﻿Ext.define('Happy.navigation.shell.view.NavigationPanel', {
    extend: 'Ext.tab.Panel',
    alias: 'widget.shell-navigation-panel',
    requires: ['Happy.Ajax'],

    title: '导航菜单',
    tabPosition: 'left',

    onRender: function () {
        var me = this;

        me.callParent(arguments);

        me.loadItems();
    },

    loadItems: function () {
        var me = this;

        Happy.Ajax.callAction({
            url: '/Happy/Navigation/Menu/Fetch',
            params: { query: {} },
            success: function (result) {
                var roots = Ext.Array.filter(result.items, function (item) {
                    return !item.ParentId;
                });

                var trees = Ext.Array.map(roots, function (root) {
                    return {
                        title: root.Title,
                        xtype: 'treepanel',
                        rootVisible: false,
                        root: me.buildRoot(result.items, root)
                    };
                });

                trees = me.add(trees);

                Ext.Array.each(trees, function (tree) {
                    me.relayEvents(tree, ['itemclick']);
                });

                me.setActiveTab(0);
            }
        });
    },

    buildRoot: function (items, root) {
        var me = this;

        Ext.apply(root, {
            id: root.Id,
            text: root.Title,
            leaf: !!root.Url
        });

        var children = Ext.Array.filter(items, function (item) {
            return item.ParentId == root.Id;
        });
        Ext.Array.each(children, function (item) {
            me.buildRoot(items, item);
        });
        if (children.length > 0) {
            root.children = children;
        }

        return root;
    }
});